package com.lysj.bhp.wallet.controller;

import com.lysj.bhp.wallet.base.WalletContent;
import com.lysj.bhp.wallet.domain.EthereumWallet;
import com.lysj.bhp.wallet.util.EtherScanUtil;
import com.lysj.bhp.wallet.util.Web3jUtils;
import com.lysj.bhp.recharge.domain.RechargeRecord;
import com.lysj.bhp.system.base.BaseConst;
import com.lysj.bhp.user.domain.User;
import com.lysj.bhp.util.web.ParamUtil;
import com.lysj.bhp.util.web.Resp;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.web3j.crypto.WalletUtils;

import java.io.File;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Date;

@RestController
@RequestMapping("/ethereum_wallet")
public class EthereumWalletController extends WalletContent {

    private Logger logger = LoggerFactory.getLogger(EthereumWalletController.class);


    @ApiOperation(value = "获取一个以太坊钱包", notes = "一个账号只能创建一个钱包")
    @PostMapping("/my_ethereum_wallet")
    public Resp myEthereumWallet() throws Exception {
        EthereumWallet ethereumWalletQuery = ethereumWalletRepository.findByUserId(currentUser().getUserId());
        if (ethereumWalletQuery != null) {
            return new Resp(Resp.SUCCESS, "您已经有一个以太坊钱包了,请不要重复创建", "0x" + ethereumWalletQuery.getAddress());
        }
        String password = ParamUtil.uuid();
        String keystoreFilename = WalletUtils.generateFullNewWalletFile(password, new File(BaseConst.KEY_STORE_DIR));

        String[] addressArray = keystoreFilename.split("--");
        String address = addressArray[2].substring(0, 40);

        EthereumWallet ethereum = new EthereumWallet();
        ethereum.setKeystore(keystoreFilename);
        ethereum.setPassword(password);
        ethereum.setUserId(currentUser().getUserId());
        ethereum.setAddress(address);
        ethereum.setBalance(BigDecimal.ZERO);
        ethereum.setFreezeBalance(BigDecimal.ZERO);
        ethereum.setAvailBalance(BigDecimal.ZERO);
        ethereum.setBookKeepBalance(BigDecimal.ZERO);
        logger.info(ethereum.toString());
        ethereumWalletRepository.save(ethereum);
        return new Resp(Resp.SUCCESS, "创建以太币钱包成功", "0x" + ethereum.getAddress());
    }


    @ApiOperation(value = "刷新用户以太币钱包", notes = "")
    @PostMapping("/refresh_ether_wallet")
    public Resp refreshEtherWallet(Long userId) throws Exception {
        User user = userRepository.findOne(userId);
        if (user == null) {
            return new Resp(Resp.PARAM_ERROR, "用户不存在");
        }
        logger.info("开始手动刷新以太币钱包，用户Id:" + user.getUserId());
        EthereumWallet ethereumWallet = ethereumWalletRepository.findByUserId(userId);
        if (ethereumWallet == null) {
            return new Resp(Resp.PARAM_ERROR, "该用户没有创建以太币钱包");
        }
        BigInteger realBalance = EtherScanUtil.getBalance(ethereumWallet.getAddress());
        System.out.println("接口返回的以太坊币为：" + realBalance);
        if (realBalance.longValue() < 0) { //
            return new Resp(Resp.PARAM_ERROR, "接口返回错误的值");
        }

        BigDecimal bigDecimal = Web3jUtils.weiToEther(realBalance);
//        System.out.println(bigDecimal);
//        System.out.println(bigDecimal.doubleValue());
        int r = bigDecimal.compareTo(ethereumWallet.getBalance());
        if (r == -1) { //查询到的余额小于钱包得真实余额，则更新
            ethereumWallet.setBalance(bigDecimal);
        } else {
            logger.info("查询到以太坊钱包余额增加，开始记录");
            BigDecimal increase = bigDecimal.subtract(ethereumWallet.getBalance()); // 增加的余额

            ethereumWallet.setBalance(bigDecimal);
            // 创建充值记录
            RechargeRecord rechargeRecord = new RechargeRecord();
            rechargeRecord.setCoinType(2);
            rechargeRecord.setPayAmount(increase);
            rechargeRecord.setUserId(ethereumWallet.getUserId());
            rechargeRecord.setCreateTime(new Date());
            rechargeRecordRepository.save(rechargeRecord);
            userRepository.save(user);
        }
        ethereumWallet.setLastQueryTime(System.currentTimeMillis()); // 将最近的查询时间设置为现在
        ethereumWalletRepository.save(ethereumWallet);
        return new Resp("手动刷新成功");
    }


}
